import store from './store'
import router from './router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'

// 路由白名单
let whiteList = ['/login', '/404']

router.beforeEach(async (to, from, next) => {
  nprogress.start()
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (!store.getters.userId) {
        let userInfo = await store.dispatch('user/getUserInfo')
        let routes = await store.dispatch('permission/getAsyncRoutes', userInfo.roles.menus);
        // 把筛选处理来的路由对象，加到路由规则里
        // 把路由的对象添加路由规则(添加的一堆规则，既然是一堆规则就是一个数组)
        router.addRoutes(routes)
        next(to.path)
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

router.afterEach((to, from, next) => {
  nprogress.done()
})
